package com.yaodian100.ec.outlet.service.impl;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.impl.DomainServiceImpl;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.template.service.TemplateService;
import com.yaodian100.ec.outlet.entity.Outlet;
import com.yaodian100.ec.outlet.service.OutletService;

/**
 * 
 * @author scott.su
 *
 */
public class OutletServiceImpl extends DomainServiceImpl<Outlet> implements OutletService {

	@Autowired
	private TemplateService templateService;
	
	@Override
	public Outlet get(Serializable oid) throws CoreException {
		return super.get(oid);
	}
	
	@Override
	@Transactional(readOnly = false)
	public void delete(Outlet entity) throws CoreException {
		entity.setDelete(true);
		getDao().update(entity);
	}
	
	@Override
	public List<Outlet> getList(int firstResult, int maxResults,
			CommonCriteria criteria, String[] sortOrder) throws CoreException {
		if (criteria == null) {
			criteria = new CommonCriteria();
		}
		criteria.addEq("delete", false);
		return super.getList(firstResult, maxResults, criteria, sortOrder);
	}
	
	@Override
	public Number getListSize(CommonCriteria criteria) throws CoreException {
		if (criteria == null) {
			criteria = new CommonCriteria();
		}
		criteria.addEq("delete", false);
		return super.getListSize(criteria);
	}
	
	@Override
	public List<Outlet> getAll(int firstResult, int maxResults,
			String[] sortOrder) throws CoreException {
		CommonCriteria criteria = new CommonCriteria();
		criteria.addEq("delete", false);
		return getList(0, -1, criteria, sortOrder);
	}
	
	@Override
	public Number getAllSize() throws CoreException {
		CommonCriteria criteria = new CommonCriteria();
		criteria.addEq("delete", false);
		return getListSize(criteria);
	}
	
	public boolean validateCampaignTime(Outlet outlet) throws CoreException {
		StringBuilder sb = new StringBuilder();
		sb
		.append("SELECT ID FROM EC_OUTLET_CAMPAIGN ")
		.append("WHERE BRAND_CATEGORY_ID = ? ")
		.append("AND IS_DELETE = 0 ")
		.append("AND ID NOT IN ( ")
		.append("SELECT A.ID FROM EC_OUTLET_CAMPAIGN A ")
		.append("WHERE A.IS_DELETE = 0 ")
		//.append("AND A.IS_ENABLE = 1 ")
		.append("AND A.BRAND_CATEGORY_ID = ? ")
		.append("AND (A.START_DATE > ? ") // ?:endDate
		.append("OR A.END_DATE < ?) ") // ?:startDate
		.append(") ");
		if( outlet.getId() != null )
			sb.append("AND ID <> ? ");
		
		List attrs = new ArrayList();
		attrs.add(outlet.getBrandCategoryId());
		attrs.add(outlet.getBrandCategoryId());
		attrs.add(outlet.getEndDate());
		attrs.add(outlet.getStartDate());
		if( outlet.getId() != null )
			attrs.add(outlet.getId());
		List ids = getDao().getSQLQueryByList(sb.toString(), attrs, 0, -1);
		
		if( ids.size() > 0 )
			return false;
		else 
			return true;
	}
	
	@Override
	public boolean generateOutletList(String date) throws ParseException, CoreException, IOException {
		DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		Date genTime = df.parse(date);
		
		// 已开卖活动
		CommonCriteria criteria = new CommonCriteria();
		criteria.addEq("enable", true);
		criteria.addGe("endDate", genTime);
		criteria.addLe("startDate", genTime);
		List<Outlet> onlineList = getList(0, -1, criteria, new String[]{"startDate desc"});
		
		// 未开卖IDS
		List<Long> comingSoonIds = new ArrayList<Long>();
		List<Outlet> comingSoonList = new ArrayList<Outlet>();
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT ID FROM EC_OUTLET_CAMPAIGN ")
			.append("WHERE IS_DELETE = 0 ")
			.append("AND IS_ENABLE = 1 ")
			.append("AND SYSDATE < START_DATE ");
		List ids = getDao().getSQLQueryByList(sb.toString(), null, 0, -1);
		
		if(ids != null && ids.size() > 0) {
			for(Object obj : ids) {
				comingSoonIds.add(new Long(obj.toString()));
			}
			
			criteria = new CommonCriteria();
			criteria.addIn("id", comingSoonIds);
			comingSoonList = getList(0, -1, criteria, new String[]{"startDate asc"});
		}
		
		// TODO 寄错误信(不用寄)
		
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("onlineList", onlineList);
		m.put("comingSoonList", comingSoonList);
		
		StringBuilder htmlFilePath = new StringBuilder();
		htmlFilePath.append(ServerValue.getFrontContentHtmlPath())
					.append("COMMON").append(File.separator)
					.append("OUTLET").append(File.separator)
					.append("OUTLET_LIST.html");
		
		FileUtils.writeStringToFile(new File(htmlFilePath.toString()), templateService.format("static_OutletList", m));
		
		return true;
	}
	
	@Override
	public boolean generateOutletCalendar(String date) throws ParseException, CoreException, IOException {
		DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		DateFormat df2 = new SimpleDateFormat("MM/dd");
		Date genTime = df.parse(date);
		
		Calendar cal = Calendar.getInstance();
		cal.setTime(genTime);
		
		List<String> dateList = new ArrayList<String>();
		List<List<Outlet>> outletList = new ArrayList<List<Outlet>>();
		for(int i = 0; i < 7; i++) {
			if( i > 0 )
				cal.add(Calendar.DATE, 1); 
				
			int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
			dateList.add(getWeekName(dayOfWeek) + df2.format(cal.getTime()));
			
			CommonCriteria criteria = new CommonCriteria();
			criteria.addEq("enable", true);
			criteria.addGe("endDate", cal.getTime());
			criteria.addLe("startDate", cal.getTime());
			List<Outlet> onlineList = getList(0, -1, criteria, new String[]{"startDate desc"});
			outletList.add(onlineList);
		}
		
		// TODO 寄错误信(不用寄)
		
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("dateList", dateList);
		m.put("outletList", outletList);
		m.put("nowTime", new Date().getTime());
		
		StringBuilder htmlFilePath = new StringBuilder();
		htmlFilePath.append(ServerValue.getFrontContentHtmlPath())
					.append("COMMON").append(File.separator)
					.append("OUTLET").append(File.separator)
					.append("OUTLET_CALENDAR.html");
		
		FileUtils.writeStringToFile(new File(htmlFilePath.toString()), templateService.format("static_OutletCalendar", m));
		
		return true;
	}
	
	private String getWeekName(int arg) {
		switch (arg) {
		case 1:
			return "星期日";
		case 2:
			return "星期一";
		case 3:
			return "星期二";
		case 4:
			return "星期三";
		case 5:
			return "星期四";
		case 6:
			return "星期五";
		case 7:
			return "星期六";
		default:
			return null;
		}
	}
	
	// Getters & Setters
	public TemplateService getTemplateService() {
		return templateService;
	}

	public void setTemplateService(TemplateService templateService) {
		this.templateService = templateService;
	}
	
}
